app.controller('TurntablCtrl', ['$scope', '$q', 'apiService',
    function(scope, $q, apiService) {
		scope.tabIndex = 1;
		scope.member = {birthyear:0, birthmonth:0, birthday:0};
		scope.years = dateUtils.getYears(0);
		scope.years.unshift('年');
		scope.months = ['月', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
		scope.genders = [{id:'男', name : '男'}, {id:'女', name : '女'}, {id:'其他', name : '其他'}];
		scope.backupMember={};
		scope.picurl='';
		scope.provinces = angular.copy(common_provinces);
		scope.picker='';
		scope.disableBirthFlag=false;
		scope.purchases = [];
		scope.products = [];
		scope.picurl='';
		var running = false;
		var minPoint = 100;
		var pid = 0;
		scope.memberLoading=true;
		
		var map = {1:320, 2:260, 3:200, 4:140, 5:80, 6:20};
		
		scope.levelMap = {1:'一', 2: '二', 3: '三', 4 : '四', 5 :'五', 6 : '六'};
		
		scope.decodeURI=function(str){
			return decodeURI(str);
		}
		
		//初始化操作
		var init = function(){
			//初始化个人信息
			loadMember();
			//初始化奖品
			loadPrizes();
			
		};
		//地址选择器
		var picker = new mui.PopPicker({
			layer: 3
		}); 
		picker.setData(common_provinces);
		//保存个人信息
		scope.saveInfo = function(){
			var message = scope.checkMember();
			if(message){
				showErrorMsg(message);
				return;
			}
			var member = {
					tel : scope.member.tel,
					name : scope.member.name,
					gender : scope.member.gender,
					address1 : scope.province.text,
					address2 : scope.city.text,
					address3 : scope.district.text,
					address4 : (scope.member.address4 ? scope.member.address4 : ''),
				};
				console.log(member);
				apiService.put("/api/member", member).then(function(resp){
					if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
						loadMember();
						$("#materialObject").hide();
						showMsg("提交成功！奖品正在发送的路上，请您耐心等待~");
					} else {
						// todo
						if (resp && resp.data && resp.data.meta && resp.data.meta.errors && resp.data.meta.errors.length && resp.data.meta.errors[0]
						&& resp.data.meta.errors[0].msg) {
							showErrorMsg(resp.data.meta.errors[0].msg);
						} else {
							showErrorMsg("系统正忙，请稍后再试");
						}
						
					}
					$('#alert button').click(function(){
						window.location.href = "http://siemens.ews.m.jaeapp.com/turntable/"+$("#stid").val();
					});
				}, function(error){
					console.log(error);
					showErrorMsg("系统正忙，请稍后再试");
				});
		}
		//校验信息
		scope.checkMember = function() {
			if(!scope.member.tel){
				return "请完善手机号码";
			}
			var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
		    if(!mobile.test(scope.member.tel)){
		    	return "请输入正确的手机号码";
		    }
			if(!scope.member.name){
				return "请完善姓名";
			}
			if(!scope.province ||!scope.province.text ||!scope.city || !scope.city.text || !scope.district || !scope.district.text){
				return "请完善省市区";
			}
			return null;
		};
		//流量填写手机号码
		scope.savePhoneInfo = function(){
			var message = scope.checkPhoneMember();
			if(message){
				showErrorMsg(message);
				return;
			}
			var member = {
					tel : scope.member.tel,
					name : scope.member.name,
					gender : scope.member.gender,
					address1 : scope.province.text,
					address2 : scope.city.text,
					address3 : scope.district.text,
					address4 : (scope.member.address4 ? scope.member.address4 : '')
				};
			var recharInfo = {
					tel : scope.member.tel
			};
				console.log(member);
				apiService.put("/api/member", member).then(function(resp){
					if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
						loadMember();
						$("#flow").hide();
						apiService.put("/llt/rechargeFlow?tel="+scope.member.tel).then(function(resp){
							
						})
						showMsg("提交成功！奖品正在发送的路上，请您耐心等待~");
					} else {
						// todo
						if (resp && resp.data && resp.data.meta && resp.data.meta.errors && resp.data.meta.errors.length && resp.data.meta.errors[0]
						&& resp.data.meta.errors[0].msg) {
							showErrorMsg(resp.data.meta.errors[0].msg);
						} else {
							showErrorMsg("系统正忙，请稍后再试");
						}
						
					}
					$('#alert button').click(function(){
						window.location.href = "http://siemens.ews.m.jaeapp.com/turntable/"+$("#stid").val();
					});
				}, function(error){
					console.log(error);
					showErrorMsg("系统正忙，请稍后再试");
				});
		}
		//校验信息
		scope.checkPhoneMember = function() {
			if(!scope.member.tel){
				return "请完善手机号码";
			}
		    var mobile = /^(13[0-9]{9})|(18[0-9]{9})|(14[0-9]{9})|(17[0-9]{9})|(15[0-9]{9})$/;
		    if(!mobile.test(scope.member.tel)){
		    	return "请输入正确的手机号码";
		    }
			return null;
		};

		
		scope.openPickerData=function(){
			$('.picker input').blur();
			picker.show(function(items) {
				$("#picker").val(items[0].text+items[1].text+items[2].text);
				scope.province=items[0];
				scope.city=items[1];
				scope.district=items[2];
			})
		}
		
		var bindProvince = function() {
			if (scope.member && scope.member.address1) {
				scope.provinces.forEach(function(province){
					if (province && province.text == scope.member.address1) {
						scope.province = province;
						if (scope.member.address2) {
							scope.province.children.forEach(function(city){
								if (city && city.text == scope.member.address2) {
									scope.city = city;
									if (scope.member.address3) {
										scope.city.children.forEach(function(district){
											if (district && district.text == scope.member.address3) {
												scope.district = district;
												return false;
											}
										});
									}
									return false;
								}
							});
						}
						return false;
					}
				});
			}
			scope.picker=((!scope.member.address1)?'':scope.member.address1)+''+((!scope.member.address2)?'':scope.member.address2)+''+((!scope.member.address3)?'':scope.member.address3);

		};
		
		
		var loadMember = function() {
			apiService.get("/api/member").then(function(resp){
				if (resp && resp.data && resp.data.meta && resp.data.meta.success) {
					scope.member = resp.data.data;
					bindProvince();
				} else {
					// todo
				}
				scope.memberLoading=false;
			}, function(error){
				console.log(error);
				scope.memberLoading=false;
			});
			
			apiService.get("/api/member/img").then(function(resp){
				if (resp && resp.data && resp.data.data) {
					scope.picurl = resp.data.data;	
					console.log(resp.data.data);
				} else {
					// todo
				}
			}, function(error){
				console.log(error);
			});
		};
		
		var loadPrizes = function() {
			apiService.get("/draw/top5").then(function(resp){
				if (resp && resp.data) {
					scope.prizes = resp.data;
					console.log(scope.prizes);
					
					var $list = $('.lucky-list');
			          var $inner = $('.lucky-list-inner');
			          var time = ($inner.innerWidth() / $list.innerWidth() * 6).toFixed(0) + 's';
			          $inner.css({
			            '-webkit-animation-duration': '15s',
			            '-moz-animation-duration': '15s',
			            '-o-animation-duration':'15s',
			            'animation-duration': '15s',
			          });
				} else {
					// todo
				}
			}, function(error){
				console.log(error);
			});
			 
		};
		
		
		scope.luckydraw = function() {
			if(scope.memberLoading){
				return;
			}
//			if (!scope.member || !scope.member.tel) {
//				$('.alert-error button').click(function(){
//					window.location.href = "https://siemens.ews.m.jaeapp.com/profile/"+$("#stid").val();
//				});
//				showErrorMsg("请先完善个人信息");
//				return;
//			}
			if (running) {
				return ;
			}
			running = true;
			
			if (scope.member && scope.member.points && scope.member.points[0].totalActivePoints >= minPoint) {
				emptyRotate();
				apiService.get("/draw").then(function(resp){
					if (resp && resp.data && resp.data.success) {
						scope.member.points[0].totalActivePoints-=100;
						setTimeout(function(){loadMember();},4000);
						var level = resp.data.prizeLevel;
							rotateFunc(level, map[level], "恭喜您中了" + scope.levelMap[level]+ "等奖: " + resp.data.prizeName+".");
					} else {
						running = false;
						if (resp && resp.data && resp.data.message) {
							showErrorMsg("抽奖失败：" + resp.data.message);
						} else {
							showErrorMsg("抽奖人数爆满,请稍后再试!");
						}
						$rotateBody.stopRotate();
					}
				}, function(error){
					running = false;
					showErrorMsg("抽奖人数爆满,请稍后再试!");
					$rotateBody.stopRotate();
				});
				
			} else {
				running = false;
				showErrorMsg("你的抽奖积分不足，不能抽奖")
				return;
			}
		};
		
		 var $plateBtn = $('#plateBtn');
         var $rotateBody = $('#rotateBody');

		var emptyRotate = function() {
			$rotateBody.stopRotate();
			$rotateBody.rotate({
				angle : 0,
				duration : 1000 * 60,
				animateTo : 360 * 60,
				callback : function() {
					showErrorMsg("抽奖人数爆满,请稍后再试!", true);
				}
			});
		};
		
		var rotateFunc = function(awards, angle, text) { // awards:奖项，angle:奖项对应的角度
			$rotateBody.stopRotate();
			$rotateBody.rotate({
				angle : 0,
				duration : 5000,
				animateTo : angle + 1440, // angle是图片上各奖项对应的角度，1440是让指针固定旋转4圈
				callback : function() {
					if(awards==1 || awards==5 || awards==6 || (awards==4 && scope.member.tel!='')){
						showMsg(text, true);
					}else if(awards==2 || awards==3){
						showMaterialObject(text,true);
					}else{
						showFlow(text,true);
					}
					running = false;
				}
			});
		};
		
		var showMsg = function(msg, apply) {
			scope.msg = msg;
			if (apply) {
				scope.$apply();
			}
			if ($('#alert').hasClass('hide')) {
				$('#alert').removeClass('hide');
			}
		};
		
		var showMaterialObject = function(msg, apply) {
			scope.msg = msg;
			if (apply) {
				scope.$apply();
			}
			if ($('#materialObject').hasClass('hide')) {
				$('#materialObject').removeClass('hide');
			}
		};
		
		var showFlow = function(msg, apply) {
			scope.msg = msg;
			if (apply) {
				scope.$apply();
			}
			if ($('#flow').hasClass('hide')) {
				$('#flow').removeClass('hide');
			}
		};
		
		
		var showErrorMsg = function(msg, apply) {
			scope.msg = msg;
			if (apply) {
				scope.$apply();
			}
			if ($('.alert-error').hasClass('hide')) {
				$('.alert-error').removeClass('hide');
			}
			
		};
		
		init();
		
	}
]);

$('#alert button').click(function() {
	if (!$('#alert').hasClass('hide')) {
		$('#alert').addClass('hide');
	}
});

$('.alert-error button').click(function() {
	if (!$('.alert-error').hasClass('hide')) {
		$('.alert-error').addClass('hide');
	}
});


